package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Business;
import cn.wolfcode.qo.BusinessQueryObject;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IBusinessService;
import cn.wolfcode.utils.FileUploadUtil;
import cn.wolfcode.utils.RequestPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Random;

@Controller
@RequestMapping("/business")
public class BusinessController {

    private IBusinessService businessService ;
    @Autowired
    public void setBusinessService(IBusinessService businessService) {
        this.businessService = businessService;
    }

    @RequestMapping("/list")
    public String list(Model model , @ModelAttribute("qo")BusinessQueryObject qo){
        PageInfo<Business> pageInfo = businessService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
         return "business/list" ;
    }




    @RequestMapping("/input")
    public String input(Long id,Model model){
        if (id != null) {
            model.addAttribute("business",businessService.selectById(id));
        }
        return "/business/input" ;
    }

    @RequestMapping("/save")
    public String save(Business business , MultipartFile file , HttpServletRequest request) throws Exception {
        if (file!=null && file.getSize()>0){
            String realPath = request.getServletContext().getRealPath("");
            String uploadFile = FileUploadUtil.uploadFile(file, realPath);
            business.setLicenseImg(uploadFile);
        }

        if (business.getId() != null){
            businessService.update(business);
            return "redirect:/business/list";
        }
        businessService.insert(business);

   return "redirect:/business/list";

    }

}
